package org.beholder;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Enumeration;

/**
 * Designed to process image data sent as a body of simple Http POST request 
 * and store image in DB.
 */
public class UploadServlet extends AbstractServlet {

    private static final long serialVersionUID = 1L;
//    private ByteArrayInputStream bais = new ByteArrayInputStream();

    private Logger logger = Logger.getLogger(UploadServlet.class);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(">>>");
        System.out.println("Date is "+(new Date()));
        System.out.println("req.getPathInfo()="+req.getPathInfo());
        System.out.println("req.getPathTranslated()="+req.getPathTranslated());
        System.out.println("req.getRemoteAddr()=" + req.getRemoteAddr());
        System.out.println("req.getRemoteUser()=" + req.getRemoteUser());
        Enumeration e = req.getHeaderNames();
        while(e.hasMoreElements()) {
            String headerName = (String)e.nextElement();
            String headerValue = req.getHeader(headerName);
            System.out.println("Header name=" + headerName + ", value=" + headerValue);
        }
        System.out.println("<<<");
        String sessionId = req.getSession().getId();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        IOUtils.copy(req.getInputStream(), os);
        IOUtils.closeQuietly(req.getInputStream());
        System.out.println("Body size:"+os.size());
        if (STATE_PRW.equals(getSettings().get(STATE_PARAM))) {
            storePreview(os.toByteArray());
	        resp.getOutputStream().write(getCode());
        } else if (STATE_REC.equals(getSettings().get(STATE_PARAM))) {
            storePreview(os.toByteArray());
            storeShot(os.toByteArray(), sessionId);
            resp.getOutputStream().write(getCode());
        } else if (STATE_HD.equals(getSettings().get(STATE_PARAM))) {
            storePreview(os.toByteArray());
            storeShot(os.toByteArray(), sessionId);
            resp.getOutputStream().write(getCode());
        }
        os.reset();
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.flushBuffer();
    }

    private byte getCode () {
        String code = System.getProperty("state")==null?"0":System.getProperty("state");
        return (byte)(code.getBytes()[0]-48);
    }

}
